<?php

namespace App\Services;

class TreeConverter
{
    /**
     * 生成随机10位ID
     */
    public static function generateRandomId($length = 10)
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    /**
     * 将扁平数据转换为三级树形结构
     */
    public function convertToTreeStructure($data)
    {
        $level1Map = []; // 存储一级节点
        $level2Map = []; // 存储二级节点
        $result = [];

        foreach ($data as $item) {
            $path = str_replace('/', ',', $item['namePath']);
            $parts = explode(',', $path);
            
            if (count($parts) !== 3) {
                continue;
            }

            list($l1, $l2, $l3) = array_map('trim', $parts);

            // 处理一级节点
            if (!isset($level1Map[$l1])) {
                $level1Id = self::generateRandomId();
                $level1Map[$l1] = [
                    'id' => $level1Id,
                    'id_path' => ',' . $level1Id . ',',
                    'is_leaf' => 2,
                    'level' => 1,
                    'name' => $l1,
                    'name_path' => $l1,
                    'parent_id' => 0,
                    'children' => []
                ];
                $result[] = &$level1Map[$l1];
            }

            // 处理二级节点
            $l2Key = $l1 . '|' . $l2;
            if (!isset($level2Map[$l2Key])) {
                $level2Id = self::generateRandomId();
                $level2Map[$l2Key] = [
                    'id' => $level2Id,
                    'id_path' => $level1Map[$l1]['id_path'] . $level2Id . ',',
                    'is_leaf' => 2,
                    'level' => 2,
                    'name' => $l2,
                    'name_path' => $l1 . ',' . $l2,
                    'parent_id' => $level1Map[$l1]['id'],
                    'children' => []
                ];
                $level1Map[$l1]['children'][] = &$level2Map[$l2Key];
            }

            // 处理三级节点（叶子节点）
            $level3Node = [
                'id' => (string)$item['id'],
                'id_path' => $level2Map[$l2Key]['id_path'] . $item['id'] . ',',
                'is_leaf' => 1,
                'level' => 3,
                'name' => $item['name'],
                'name_path' => $l1 . ',' . $l2 . ',' . $l3,
                'parent_id' => $level2Map[$l2Key]['id']
                // 叶子节点没有 children 字段
            ];

            $level2Map[$l2Key]['children'][] = $level3Node;
        }

        return $result;
    }

    /**
     * 格式化树形结构输出
     */
    public function formatTreeOutput($tree)
    {
        return json_encode($tree, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }
}